package mspbots.tsheets.client.core.app;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.tsheets.client.core.AbstractToolsUtil;
import mspbots.tsheets.client.core.BaseSyncService;
import mspbots.tsheets.client.core.SyncRequest;
import mspbots.tsheets.client.core.TokenState;
import mspbots.tsheets.common.QueryParams;
import mspbots.tsheets.common.RedisKeys;
import mspbots.tsheets.common.ResultSync;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Map;

/**
 * mspbots.timesheet.client.core.app.TimeSheetServiceImpl
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/10/28
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class AppServiceImpl extends AbstractToolsUtil {

    private final Map<String, BaseSyncService> syncServiceMap;

    public Mono<Boolean> onOff(Long tenantId, String onOff) {
        if ("ON".equals(onOff.toUpperCase())) {
            return this.stringRedisTemplate.opsForValue()
                    .set(RedisKeys.ON_OFF_TENANT_TASK_REDIS_KEY + ":" + tenantId, onOff.toUpperCase(),
                            Duration.ofDays(365));
        } else {
            return this.stringRedisTemplate.opsForValue()
                    .delete(RedisKeys.ON_OFF_TENANT_TASK_REDIS_KEY + ":" + tenantId);
        }
    }

    public Mono<JsonNode> initialize(TokenState tokenState) {
        ResultSync resultSync = ResultSync.withDefault(tokenState.getTenantId(), "TEST-SECURITY");
        return super.sheetsClient.get("/current_user", QueryParams.withDefault())
                .subscriberContext(ctx -> ctx.put("token", tokenState))
                .subscriberContext(ctx -> ctx.put("resultSync", resultSync))
                .doOnNext(result -> this.reactiveRedisTemplate.opsForValue()
                        .set(RedisKeys.TENANT_PROPERTIES_REDIS_KEY_PREFIX + tokenState.getTenantId(), tokenState,
                                Duration.ofDays(36500)).subscribe(res -> log.info("save configuration is success")))
                .doOnSuccess(result -> Flux.fromStream(this.syncServiceMap.values().parallelStream())
                        .flatMap(v -> Flux.concatDelayError(v.syncFast(tokenState), v.syncSlower(tokenState),
                                v.syncSlow(tokenState))).subscribe());
    }

    public Mono<ObjectNode> synchronise(Long tenantId, SyncRequest syncRequest) {
        return Mono.just(this.objectMapper.createObjectNode().put("result", "success"))
                .doOnSuccess(res -> this.reactiveRedisTemplate.opsForValue().
                        get(RedisKeys.TENANT_PROPERTIES_REDIS_KEY_PREFIX + tenantId)
                        .map(data -> this.objectMapper.convertValue(data, TokenState.class))
                        .flatMapMany(tokenState -> Flux.fromStream(this.syncServiceMap.values().parallelStream())
                                .flatMap(v -> v.manualSync(tokenState, syncRequest)))
                        .subscribe(result -> log.info("Synchronise manual sync success."),
                                err -> log.error("Synchronise manual sync error, msg: {}", err.getMessage())));
    }
}
